/**
 * Created by lichong on 2017/7/16.
 */

import React from 'react';
import {Table, Input, Popconfirm} from 'antd';
import EditableCell from './EditableCell';

class EditableTable extends React.Component{

    constructor(props) {
        super(props);
    }

    state = {
        data:[],
    }
    
    renderColumns(data, rowIndex, columnIndex, text) {
        const columnDef = this.columns[columnIndex];
        const { editable, status , displayType } = data[rowIndex][columnDef.dataIndex];
        if (displayType === 'fixedValue') {
            return text;
        }
        return (<EditableCell
            editable={editable}
            value={text}
            form={this.props.form}
            prodIndex={this.props.prodIndex}
            columnDef={columnDef}
            dataIndex={columnDef.dataIndex}
            onChange={value => this.handleChange(columnDef.dataIndex, rowIndex, value)}
            status={status}
        />);
    }
    handleChange(key, index, value) {
        const data = this.getData();
        data[index][key].value = value;
        this.setState({ data });
    }
    edit(index) {
        const data = this.getData();
        Object.keys(data[index]).forEach((item) => {
            if (data[index][item] && typeof data[index][item].editable !== 'undefined') {
                data[index][item].editable = true;
            }
        });
        this.setState({ data });
    }
    editDone(index, type) {
        const data = this.getData();
        Object.keys(data[index]).forEach((item) => {
            if (data[index][item] && typeof data[index][item].editable !== 'undefined') {
                data[index][item].editable = false;
                data[index][item].status = type;
            }
        });
        this.setState({ data }, () => {
            Object.keys(data[index]).forEach((item) => {
                if (data[index][item] && typeof data[index][item].editable !== 'undefined') {
                    delete data[index][item].status;
                }
            });
        });
    }
    getData(){
        return this.state.data;
    }

    render() {
        const data = this.getData();
        const dataSource = data.map((item) => {
            const obj = {};
            Object.keys(item).forEach((key) => {
                obj[key] = key === 'key' ? item[key] : item[key].value;
            });
            return obj;
        });
        const columns = this.columns;
        return <Table bordered dataSource={dataSource} columns={columns} pagination={this.props.pagination}/>;
    }

}

export default EditableTable;